<template>
  <div>
    <el-tabs v-model="currentName" type="card" @tab-click="handleClick">
      <el-tab-pane
        v-for="item in progressList"
        :key="item.id"
        :label="item.portName"
        :name="item.portName"
        class="green-word"
      ></el-tab-pane>
    </el-tabs>
    <div class="taskside-title">
      <div class="class_taskside">
        <div>{{ projectName }}</div>
        <el-row type="flex" class="statistics-div" justify="flex-end">
          <el-col class="rh" style="margin-bottom: 4px">
            <el-button type="danger" @click="handleBatchdelete" size="small"
              >批量删除</el-button
            >
            <el-button
              :disabled="!authority.affirmPointUser"
              type="primary"
              v-if="!selectAllChange && !editstate"
              @click="saveProgress"
              size="small"
              >保存进度</el-button
            >
            <el-button
              :disabled="!authority.affirmPointUser"
              type="primary"
              size="small"
              :class="
                authority.affirmPointUser ? 'green-btn common-btn-wd' : ''
              "
              @click="confirmMember"
            >
              <span v-if="editstate || selectAllChange">确定人员安排</span>
              <span v-else>修改人员安排</span>
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="pointList"
      border
      style="margin-bottom: 30px"
      :header-cell-style="{ background: '#F9F9F9' }"
      align="center"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column
        label="序号"
        width="50"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        prop="levelOneModule"
        label="一级模块"
        align="center"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="levelTwoModule"
        label="二级模块"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="functionDesc"
        label="功能描述"
        align="center"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="type"
        label="类型"
        align="center"
        width="80"
      ></el-table-column>
      <el-table-column label="界面" align="center" width="120">
        <template slot-scope="scope">
          <div
            v-if="
              (selectAllChange || scope.row.affirmUser !== 1) &&
              scope.row.pageDevStatus !== 2
            "
          >
            <el-select
              v-model="scope.row.pageUserId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in pageUsers"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
          <div v-else class="schedule">
            <span>{{ scope.row.pageName }}</span>
            <div @click="clickTopagestate(scope.row)" class="schedule-text">
              <span v-if="scope.row.pageDevStatus === 0" class="onecount"
                >未开始</span
              >
              <span v-else-if="scope.row.pageDevStatus === 1" class="twocount"
                >进行中</span
              >
              <span v-else class="threecount">已完成</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="JAVA" align="center" width="120">
        <template
          slot-scope="scope"
          v-if="javaUsers.length > 0 && isjava === 1"
        >
          <div
            v-if="
              (selectAllChange || scope.row.affirmUser !== 1) &&
              scope.row.javaDevStatus !== 2
            "
          >
            <el-select
              v-model="scope.row.javaUserId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in javaUsers"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>

          <div v-else class="schedule">
            <span>{{ scope.row.javaName }}</span>
            <div @click="clickTojavastate(scope.row)" class="schedule-text">
              <span v-if="scope.row.javaDevStatus === 0" class="onecount"
                >未开始</span
              >
              <span v-else-if="scope.row.javaDevStatus === 1" class="twocount"
                >进行中</span
              >
              <span v-else class="threecount">已完成</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="interfaceTest"
        label="接口联调"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <div class="schedule" v-if="scope.row.affirmUser === 1">
            <span>{{ scope.row.pageName }}</span>
            <div @click="clickToportstate(scope.row)" class="schedule-text">
              <span v-if="scope.row.interfaceDebugStatus === 0" class="onecount"
                >未开始</span
              >
              <span
                v-else-if="scope.row.interfaceDebugStatus === 1"
                class="twocount"
                >进行中</span
              >
              <span v-else class="threecount">已完成</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="scope">
          <el-button
            :disabled="!authority.canOperatePoint"
            size="mini"
            type="primary"
            plain
            @click="handleModify(scope.$index, scope.row)"
            >修改</el-button
          >
          <el-button
            :disabled="!authority.canOperatePoint"
            size="mini"
            type="danger"
            plain
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增功能点弹框 -->
    <el-dialog
      :title="pointtitle"
      :visible.sync="dialogFormVisible"
      width="35%"
      center
      :show-close="false"
      :close-on-click-modal="false"
      @close="close('ruleForm')"
    >
      <el-form
        :model="ruleForm"
        label-width="100px"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item label="一级模块" prop="levelOneModule">
          <el-input v-model="ruleForm.levelOneModule"></el-input>
        </el-form-item>
        <el-form-item label="二级模块" prop="levelTwoModule">
          <el-input v-model="ruleForm.levelTwoModule"></el-input>
        </el-form-item>
        <el-form-item label="功能描述" prop="functionDesc">
          <el-input
            type="textarea"
            v-model="ruleForm.functionDesc"
            rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择类型">
            <el-option label="新增" value="新增"></el-option>
            <el-option label="修改" value="修改"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickaddPoint">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import bus from "@/components/bus";
import {
  getVerTaskPortList,
  getFunctionPointList,
  getpointDeveloperList,
  putpointDevStatusModify,
  postfunctionPointAddOne,
  postpointDeveloperConfirm,
  putpointModify,
  deletepointDelete,
  deletebatchDeletePoint,
  getExportList,
} from "@/service/progressApi";

export default {
  props: ["authority"],
  data() {
    return {
      projectName: this.$route.query.projectName,
      pointtitle: "",
      tasktitle: "",
      versionId: this.$route.query.versionId,
      currentName: "",
      portIds: "",

      editstate: false, //控制新增/导入初始状态开关（同selectAllChange同步双开关）
      selectAllChange: false, //控制全部统一修改开关

      progressList: [],
      InterCount: 0, // 接口联调完成数
      pointCount: 0, // 总功能点数
      pageCount: 0, // 界面完成数
      isjava: null, //是否分配Java
      pointList: [],
      featureid: "", //功能点id
      conduct: 0,
      tableData: [],
      javaUsers: [], //java人员列表

      interFace: "",
      allportIds: "", //全部任务端id
      pageUsers: [], //界面安排人员列表
      pointrow: [], //确定开发人员提交
      dialogFormVisible: false,
      ruleForm: {
        levelOneModule: "", //一级模块
        levelTwoModule: "", //二级模块
        type: "", //类型，新增/修改
        functionDesc: "", //功能点描述
      },
      rules: {
        levelOneModule: [
          {
            required: true,
            message: "请输入一级模块",
            trigger: "blur",
          },
        ],
        levelTwoModule: [
          {
            required: true,
            message: "请输入二级模块",
            trigger: "blur",
          },
        ],
        functionDesc: [
          {
            required: true,
            message: "请输入功能点描述",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change",
          },
        ],
      },
      loading: false,
      removeId: [], //批量刪除
    };
  },
  created() {
    this.verTaskPortlistData();
  },
  mounted() {},
  methods: {
    //监听新增功能点弹框的关闭事件
    close(formName) {
      this.$refs[formName].resetFields();
    },
    //导出功能列表
    exportFunctionList() {
      this.progressList.forEach((el) => {
        this.allportIds += el.id + ",";
      });
      console.log(this.allportIds);
      // window.location.href = `${this.$img}/api/admin/functionPoint/pointExport/${this.allportIds}`; //测试
      // window.location.href = `https://oa2.douziit.com/api/admin/functionPoint/pointExport/${this.allportIds}`; //正式
      getExportList(this.allportIds).then((res) => {
        console.log(res);
        let blob = new Blob([res], {
          type: "application/vnd.ms-excel",
        });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        // link.download = this.row.riskUnit + this.row.riskAddr + "危险告知卡";
        link.click();
        URL.revokeObjectURL(url); // 释放内存
      });
    },
    addPoint() {
      this.pointtitle = "新增功能点";
      this.dialogFormVisible = true;
    },
    submitForm(formName) {
      let bool;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          bool = true;
        } else {
          console.log("error submit!!");
          bool = false;
        }
      });
      return bool;
    },

    // 添加某个任务端下的功能点
    clickaddPoint() {
      if (this.submitForm("ruleForm")) {
        if (this.pointtitle == "新增功能点") {
          postfunctionPointAddOne({
            portId: this.portIds,
            levelOneModule: this.ruleForm.levelOneModule,
            levelTwoModule: this.ruleForm.levelTwoModule,
            functionDesc: this.ruleForm.functionDesc,
            type: this.ruleForm.type,
          }).then((res) => {
            console.log("新增功能点", res);
            this.$message.success("新增成功~");
            this.dialogFormVisible = false;
            this.staffing();
          });
        } else {
          putpointModify({
            id: this.featureid,
            levelOneModule: this.ruleForm.levelOneModule,
            levelTwoModule: this.ruleForm.levelTwoModule,
            functionDesc: this.ruleForm.functionDesc,
            type: this.ruleForm.type,
          }).then((res) => {
            this.staffing();
            this.$message.success("修改成功~");
            this.dialogFormVisible = false;
          });
        }
      }
    },
    // 修改功能点
    handleModify(index, row) {
      this.pointtitle = "修改功能点";
      this.dialogFormVisible = true;
      this.featureid = row.id;
      this.$nextTick(() => {
        for (let item in this.ruleForm) {
          this.ruleForm[item] = row[item];
        }
      });
    },
    // 删除功能点
    handleDelete(index, row) {
      if (row.interfaceDebugStatus === 2 || row.javaDevStatus === 2) {
        this.$message.info("该计划中有人员已完成功能点，无法删除");
      } else {
        this.$confirm("确定 删除该功能点吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }).then(() => {
          deletepointDelete(row.id).then((res) => {
            this.staffing();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        });
      }
    },
    //任务端列表
    verTaskPortlistData() {
      getVerTaskPortList(this.versionId).then((res) => {
        this.progressList = res.data;
        if (this.progressList.length < 1) {
          this.$message.info("请先添加任务端");
        }
        this.currentName = this.progressList[0].portName
          ? this.progressList[0].portName
          : sessionStorage.getItem("currentName");
        this.portIds = this.progressList[0].id
          ? this.progressList[0].id
          : sessionStorage.getItem("portIds");
        // 人员安排列表
        this.staffing();
      });
    },
    // tab点击切换
    handleClick(tab, event) {
      console.log("点击切换", tab, event);
      this.currentName = tab.name;
      sessionStorage.setItem("currentName", this.currentName);
      // 关闭统一修改的开关
      this.selectAllChange = false;
      this.progressList.forEach((el) => {
        if (el.portName === tab.name) {
          this.portIds = el.id;
          console.log("tabID", this.portIds);
          sessionStorage.setItem("portIds", this.portIds);
        }
      });
      // 人员安排列表
      this.staffing();
    },
    // 人员安排列表
    staffing() {
      getFunctionPointList(this.portIds).then((res) => {
        this.InterCount = res.data.InterCount; // 接口联调完成数
        this.pointCount = res.data.pointCount; // 总功能点数
        this.pageCount = res.data.pageCount; // 界面完成数
        this.pointList = res.data.pointList;

        this.isjava = res.data.isJava; //该任务端是否分配java 0否  1是

        // 功能点人员安排下拉列表
        this.$nextTick(() => {
          this.pointDeveloperListData();
        });
      });
    },
    // 重构功能点列表数据
    setDataList(i) {
      this.pointList.forEach((el, index) => {
        if (el.affirmUser === 0) {
          // editstate 为true存在待确认人员
          this.editstate = true;
          // 重新构造数据
          this.$nextTick(() => {
            // 给待添加人员对象添加pageUserId字段(界面)，并为该字段赋值为 人员列表第一项
            if (this.pageUsers.length > 0) {
              this.$set(
                this.pointList[index],
                "pageUserId",
                this.pageUsers[i].id
              );
            }
            // 给待添加人员对象添加javaUserId字段(界面)，并为该字段赋值为 人员列表第一项
            if (this.javaUsers.length > 0) {
              this.$set(
                this.pointList[index],
                "javaUserId",
                this.javaUsers[i].id
              );
            }
          });
          return;
        } else {
          this.editstate = false;
        }
      });
    },
    // 功能点人员安排下拉列表
    pointDeveloperListData() {
      getpointDeveloperList(this.portIds).then((res) => {
        this.pageUsers = res.data.pageUsers;
        this.javaUsers = res.data.javaUsers;

        // 构造第一项
        this.setDataList(0);

        console.log("功能点全部数据", this.pointList);
        console.log("界面下拉框人员id", this.pageUsers);
        console.log("java下拉框人员id", this.javaUsers);
        //之前选择的负责人不在负责人选择下拉列表中时 将对应的人员改成下拉列表中的第一个人且需要先判断这个人的完成状态，只有非已完成状态才能修改
        this.pointList.forEach((x) => {
          if (this.pageUsers.length > 0) {
            this.pageUsers.forEach((y) => {
              // if (x.pageDevStatus !== 2 && x.pageUserId !== y.id) {
              if (x.pageDevStatus !== 2 && !x.pageUserId) {
                x.pageUserId = this.pageUsers[0].id;
              }
            });
          }
          if (this.javaUsers.length > 0) {
            this.javaUsers.forEach((z) => {
              // if (x.javaDevStatus !== 2 && x.javaUserId !== z.id) {
              if (x.javaDevStatus !== 2 && !x.javaUserId) {
                x.javaUserId = this.javaUsers[0].id;
              }
            });
          }
        });
      });
    },

    // 界面进行状态
    clickTopagestate(row) {
      if (row.canPageDevStatus == true) {
        this.loading = true;
        let pageDevStatus;
        row.pageDevStatus == 2
          ? (pageDevStatus = 0)
          : (pageDevStatus = row.pageDevStatus + 1);
        let data = {
          id: row.id,
          pageDevStatus: pageDevStatus,
        };
        putpointDevStatusModify(data).then((res) => {
          console.log(res);
          this.loading = false;
          if (res.code == 0) {
            this.$message.success("修改成功~");
            this.staffing();
          } else {
            this.$message.warning(res.message);
          }
        });
      } else {
        this.$message.info("抱歉!您没有操作权限");
      }
    },
    // java进行状态
    clickTojavastate(row) {
      console.log(row);
      if (row.canJavaDevStatus == true) {
        this.loading = true;
        let javaDevStatus;
        row.javaDevStatus == 2
          ? (javaDevStatus = 0)
          : (javaDevStatus = row.javaDevStatus + 1);
        let data = {
          id: row.id,
          javaDevStatus: javaDevStatus,
        };
        putpointDevStatusModify(data).then((res) => {
          console.log(res);
          this.loading = false;
          if (res.code == 0) {
            this.$message.success("修改成功~");
            this.staffing();
          } else {
            this.$message.warning(res.message);
          }
        });
      } else {
        this.$message.info("抱歉!您没有操作权限");
      }
    },
    // 接口进行状态
    clickToportstate(row) {
      if (row.canInterfaceDebugStatus == true) {
        this.loading = true;
        let interfaceDebugStatus;
        row.interfaceDebugStatus == 2
          ? (interfaceDebugStatus = 0)
          : (interfaceDebugStatus = row.interfaceDebugStatus + 1);
        let data = {
          id: row.id,
          interfaceDebugStatus: interfaceDebugStatus,
        };
        putpointDevStatusModify(data).then((res) => {
          this.loading = false;
          if (res.code == 0) {
            this.$message.success("修改成功~");
            this.staffing();
          } else {
            this.$message.warning(res.message);
          }
        });
      } else {
        this.$message.info("抱歉!您没有操作权限");
      }
    },
    //保存进度
    saveProgress() {
      this.editstate = true;
    },

    // 选择与全选删除
    handleSelectionChange(value) {
      this.removeId = value.map((el) => el.id);
      console.log("选中", this.removeId);
    },

    // 批量刪除
    handleBatchdelete() {
      if (this.removeId.length < 1) {
        this.$message.warning("请先勾选您要删除的功能点");
        return;
      }
      deletebatchDeletePoint(this.removeId).then((res) => {
        this.$confirm("确定删除您选择的功能点吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          // center: true,
        }).then(() => {
          if (res.code === 0) {
            this.verTaskPortlistData();
            this.$message({
              type: "success",
              message: "批量删除成功!",
            });
          } else {
            this.$message.info(res.message);
          }
        });
      });
    },
    // 修改、确定人员安排
    confirmMember() {
      if (this.editstate || this.selectAllChange) {
        this.$confirm("确定 以上人员安排吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info",
          center: true,
        }).then(() => {
          console.log(this.pointList);
          let arr = []; //修改安排人员参数
          // 功能点安排列表过滤出待添加人员
          this.pointList.forEach((el, index) => {
            let data = {};
            // affirmUser 字段为0时；改功能点为待分配
            // 统一修改时，affirmUser为1，需通过下拉框进行过滤修改过人员数据，步骤较为复杂；
            // 故传递所有分配人员数据，覆盖改变人员数据
            data = {
              id: el.id,
              pageUserId: el.pageUserId,
              javaUserId: el.javaUserId,
            };
            arr.push(data);
          });
          console.log(arr);
          // return
          postpointDeveloperConfirm(arr).then((res) => {
            if (res.code === 0) {
              // 关闭统一修改的开关
              this.selectAllChange = false;
              this.staffing();
              this.$message({
                type: "success",
                message: "人员安排成功!",
              });
            } else {
              this.$message({
                type: "info",
                message: ` ${this.currentName} 任务端人员还未安排完毕，请安排后再确认!`,
              });
            }
          });
        });
      } else {
        console.log(121212, this.pointList);
        // this.$set(this.pointList,this.pointList)
        this.selectAllChange = true;
        //  this.pointDeveloperListData();
      }
    },
  },
};
</script>

<style scoped>
.class_taskside {
  display: flex;
  width: 50%;
  justify-content: space-between;
  padding-right: 10px;
}

.green-btn {
  width: 120px;
  font-size: 14px;
  background-color: #00b98d;
  border-color: #00b98d;
}

.statistics-div {
  line-height: 40px;
}

.taskside-title {
  border: 1px solid #ededed;
  border-bottom: 0;
  line-height: 40px;
  font-size: 16px;
  color: #2f3133;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background: rgba(233, 233, 233, 1);
}

.schedule {
  display: flex;
  align-items: center;
  text-align: center;
  cursor: pointer;
  text-align: center;
  justify-content: center;
}

.schedule-text {
  margin-left: 10px;
}

.onecount {
  color: #f56c6c;
}

.twocount {
  color: #e9b21c;
}

.threecount {
  color: #409eff;
}
</style>
